package com.eatwhat.controller;

import com.eatwhat.dto.ApiResponse;
import com.eatwhat.dto.PageResult;
import com.eatwhat.entity.Food;
import com.eatwhat.service.FoodService;
import com.eatwhat.service.UserChoiceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/api/foods")
@CrossOrigin
public class FoodController {
    
    @Autowired
    private FoodService foodService;
    
    @Autowired
    private UserChoiceService userChoiceService;
    
    @GetMapping
    public ApiResponse<PageResult<Food>> getFoodsByPage(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        PageResult<Food> result = foodService.getFoodsByPage(page, size);
        return ApiResponse.success(result);
    }
    
    @GetMapping("/enabled")
    public ApiResponse<List<Food>> getAllEnabledFoods() {
        List<Food> foods = foodService.getAllEnabledFoods();
        return ApiResponse.success(foods);
    }
    
    @GetMapping("/{id}")
    public ApiResponse<Food> getFoodById(@PathVariable Long id) {
        Food food = foodService.getFoodById(id);
        if (food == null) {
            return ApiResponse.error("菜品不存在");
        }
        return ApiResponse.success(food);
    }
    
    @GetMapping("/category/{categoryId}")
    public ApiResponse<List<Food>> getFoodsByCategory(@PathVariable Long categoryId) {
        List<Food> foods = foodService.getFoodsByCategory(categoryId);
        return ApiResponse.success(foods);
    }
    
    @GetMapping("/search")
    public ApiResponse<List<Food>> searchFoods(@RequestParam String keyword) {
        List<Food> foods = foodService.searchFoods(keyword);
        return ApiResponse.success(foods);
    }
    
    @GetMapping("/random")
    public ApiResponse<Food> getRandomFood(HttpServletRequest request) {
        Food food = foodService.getRandomFood();
        if (food == null) {
            return ApiResponse.error("暂无可选择的菜品");
        }
        
        // 记录用户选择
        String userId = getClientId(request);
        userChoiceService.saveUserChoice(userId, food.getId());
        
        return ApiResponse.success(food);
    }
    
    @PostMapping
    public ApiResponse<Food> createFood(@RequestBody Food food) {
        try {
            Food savedFood = foodService.saveFood(food);
            return ApiResponse.success("创建成功", savedFood);
        } catch (Exception e) {
            return ApiResponse.error("创建失败：" + e.getMessage());
        }
    }
    
    @PutMapping("/{id}")
    public ApiResponse<Food> updateFood(@PathVariable Long id, @RequestBody Food food) {
        try {
            food.setId(id);
            Food savedFood = foodService.saveFood(food);
            return ApiResponse.success("更新成功", savedFood);
        } catch (Exception e) {
            return ApiResponse.error("更新失败：" + e.getMessage());
        }
    }
    
    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteFood(@PathVariable Long id) {
        try {
            foodService.deleteFood(id);
            return ApiResponse.success("删除成功", null);
        } catch (Exception e) {
            return ApiResponse.error("删除失败：" + e.getMessage());
        }
    }
    
    private String getClientId(HttpServletRequest request) {
        // 简单的客户端标识，可以根据需要改进
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        String clientIp = xForwardedFor != null ? xForwardedFor.split(",")[0] : request.getRemoteAddr();
        return clientIp;
    }
}